package demo.java.math;

import java.math.BigDecimal;
import java.util.Random;

import org.junit.Test;

/**
 * 
 * @author hanjy
 *
 */
public class BigDecimalDemo {

    public static Random random = new Random();

    @Test
    public void demo() {
        double d = Math.PI;
        String result = String.format("%.3f", d);
        System.out.println(result);
        System.out.println(roundHalfUp(d, 4));
        d = 0.00002369D;
        System.out.println("万分之" + roundHalfUp(d * 10000, 2));
    }

    @Test
    public void round() {
        System.out.println("============roundHalfUp");
        random.doubles(20).forEach(d -> {
            System.out.println(d + " = " + roundHalfUp(d, 3));
        });
        System.out.println("============roundHalfDown");
        random.doubles(20).forEach(d -> {
            System.out.println(d + " = " + roundHalfDown(d, 3));
        });
        System.out.println("============roundUp");
        random.doubles(20).forEach(d -> {
            System.out.println(d + " = " + roundUp(d, 3));
        });
        System.out.println("============roundDown");
        random.doubles(20).forEach(d -> {
            System.out.println(d + " = " + roundDown(d, 3));
        });

        System.out.println("============roundHalfEven");
        random.doubles(20).forEach(d -> {
            System.out.println(d + " = " + roundHalfEven(d, 3));
        });
    }

    /**
     * <li>BigDecimal.ROUND_HALF_UP表示四舍五入，负数先取绝对值再五舍六入再负数。
     * 
     * @param d
     * @param newScale 保留N位有效数字
     * @return
     */
    public static double roundHalfUp(double d, int newScale) {
        return new BigDecimal(d).setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * <li>BigDecimal.ROUND_HALF_DOWN也是五舍六入，负数先取绝对值再五舍六入再负数
     * 
     * @param d
     * @param newScale 保留N位有效数字
     * @return
     */
    public static double roundHalfDown(double d, int newScale) {
        return new BigDecimal(d).setScale(newScale, BigDecimal.ROUND_HALF_DOWN).doubleValue();
    }

    /**
     * <li>BigDecimal.ROUND_HALF_EVEN
     * 
     * @param d
     * @param newScale 保留N位有效数字
     * @return
     */
    public static double roundHalfEven(double d, int newScale) {
        return new BigDecimal(d).setScale(newScale, BigDecimal.ROUND_HALF_EVEN).doubleValue();
    }

    /**
     * <li>BigDecimal.ROUND_UP表示进位处理（就是直接加1）
     * 
     * @param d
     * @param newScale 保留N位有效数字
     * @return
     */
    public static double roundUp(double d, int newScale) {
        return new BigDecimal(d).setScale(newScale, BigDecimal.ROUND_UP).doubleValue();
    }

    /**
     * <li>BigDecimal.ROUND_DOWN表示直接去掉尾数
     * 
     * @param d
     * @param newScale 保留N位有效数字
     * @return
     */
    public static double roundDown(double d, int newScale) {
        return new BigDecimal(d).setScale(newScale, BigDecimal.ROUND_DOWN).doubleValue();
    }

}
